说明

这些模板是根据范神线段树模板写的(copy),基本一样,只是换成了我容易记得住的变量名。

一维线段树

单点更新

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#define lson l,m,root<<1
#define rson m+1,r,root<<1|1
const int NV = 100005;
int sum[NV<<2];
void PushUp(int root)
{
sum[root]=sum[root<<1]+sum[root<<1|1];
}
void build(int l,int r,int root=1)
{
if (l == r)
{
sum[root]=0;
return ;
}
int m = (l + r) >> 1;
build(lson);
build(rson);
PushUp(root);
}
void update(int aim,int newvalue,int l,int r,int root=1)
{
if (aim == l && l == r)
{
sum[root] += newvalue;
return ;
}
int m = (l + r) >> 1;
if (aim <= m) update(aim , newvalue , lson);
else update(aim , newvalue , rson);
PushUp(root);
}
int query(int Left,int Right,int l,int r,int root=1)
{
if (Left <= l && r <= Right)
return sum[root];
int m = (l + r) >> 1;
int ret = 0;
if (Left <= m) ret += query(Left , Right , lson);
if (m < Right) ret += query(Left , Right , rson);
return ret;
}

区间更新

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#define lson l,m,root<<1
#define rson m+1,r,root<<1|1
const int NV = 100005;
int add[NV<<2],sum[NV<<2];
void PushUp(int root)
{
sum[root]=sum[root<<1]+sum[root<<1|1];
}
void PushDown(int root,int m)
{
if (add[root])
{
add[root<<1] += add[root];
add[root<<1|1] += add[root];
sum[root<<1] += add[root] * (m - (m >> 1));
sum[root<<1|1] += add[root] * (m >> 1);
add[root] = 0;
}
}
void build(int l,int r,int root=1)
{
add[root] = 0;
if (l == r)
{
sum[root]=0;
return ;
}
int m = (l + r) >> 1;
build(lson);
build(rson);
PushUp(root);
}
void update(int Left,int Right,int newvalue,int l,int r,int root=1)
{
if (Left <= l && r <= Right)
{
add[root] += newvalue;
sum[root] += newvalue * (r - l + 1);
return ;
}
PushDown(root , r - l + 1);
int m = (l + r) >> 1;
if (Left <= m) update(Left , Right , newvalue , lson);
if (m < Right) update(Left , Right , newvalue , rson);
PushUp(root);
}
int query(int Left,int Right,int l,int r,int root=1)
{
if (Left <= l && r <= Right)
{
return sum[root];
}
PushDown(root , r - l + 1);
int m = (l + r) >> 1;
int ret = 0;
if (Left <= m) ret += query(Left , Right , lson);
if (m < Right) ret += query(Left , Right , rson);
return ret;
}